package com.springmvc.base;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class HandlerAdaptor {
    private Handler handler;

    public HandlerAdaptor(Handler handler) {
        this.handler = handler;
    }


    public Object getModelAndView(HttpServletRequest req,
                                  HttpServletResponse resp) {
        try {
            Method method = handler.getMethod();
            Object controller = handler.getController();
            Class<?>[] types = handler.getMethod().getParameterTypes();
            Object result = null;
            if(types.length==0) {
                result = method.invoke(controller);
            }else {
                Object[] params = new Object[types.length];
                for (int i=0;i<types.length;i++) {
                    if(types[i]== HttpServletRequest.class){
                        params[i] = req;
                    }
                    if(types[i]== HttpServletResponse.class){
                        params[i] = resp;
                    }
                }
                result = method.invoke(controller, params);
            }
            return result;
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return null;
    }
}
